package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.hjq.base.BaseAdapter;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.phone.R;
import com.qiantu.phone.action.StatusAction;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.event.RefreshControllerEvent;
import com.qiantu.phone.ui.adapter.SmartControllerAdapter;
import com.qiantu.phone.ui.adapter.SmartControllerCategoryAdapter;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.StatusLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 区域网关
 */
public final class LLRegionalGatewayActivity extends AppActivity implements StatusAction {

    //    private View titleView;
    private ControllerBean mControllerBean;
    private StatusLayout mStatusLayout;
    private ViewPager2 controllerViewPager;
    private RecyclerView categoryRecyclerView;
    private SmartControllerAdapter mSmartControlAdapter;
    private SmartControllerCategoryAdapter mSmartControllerCategoryAdapter;
    private int lastPositionOffsetPixels;


    public static void start(Context context, ControllerBean controllerBean) {
        Intent intent = new Intent(context, LLRegionalGatewayActivity.class);
        intent.putExtra("controllerBean", controllerBean);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_ll_regional_gateway;
    }

    @Override
    protected void initView() {
        mControllerBean = getSerializable("controllerBean");
        EventBus.getDefault().register(this);
        mStatusLayout = findViewById(R.id.status_layout);
        controllerViewPager = findViewById(R.id.controller_view_pager);
        categoryRecyclerView = findViewById(R.id.category_recycler_view);
        mSmartControlAdapter = new SmartControllerAdapter(getContext());
        controllerViewPager.setAdapter(mSmartControlAdapter);
        setRecyclerViewPadding(0, 0);
        mSmartControlAdapter.setOnChildClickListener(R.id.btn_setting, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                ControllerBean controller = mSmartControlAdapter.getData().get(position);
                ControllerDeviceAcitvity.start(getContext(), controller.getControllerSerialNo());
            }
        });
        mSmartControlAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                controllerViewPager.setCurrentItem(position);
            }
        });
        categoryRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mSmartControllerCategoryAdapter = new SmartControllerCategoryAdapter(getContext());
        categoryRecyclerView.setAdapter(mSmartControllerCategoryAdapter);
        mSmartControllerCategoryAdapter.setOnChildClickListener(R.id.controller_sort, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                Map<String, SparseArray<List<ControllerBean>>> item = mSmartControllerCategoryAdapter.getData().get(position);
                SparseArray<List<ControllerBean>> sparseArray = null;
                for(String key : item.keySet()){
                    sparseArray = item.get(key);
                }
                List<ControllerBean> normal = null;
                if(sparseArray != null){
                    normal = sparseArray.get(0);
                }
                ControllerOrderActivity.start(getContext(), "",normal);
            }
        });
        showLoading();
    }

    @Override
    protected void initData() {
        List<ControllerBean> data = new ArrayList<>();
        data.add(mControllerBean);
        showComplete();
        mSmartControlAdapter.setData(data);
        setRecyclerViewPadding(0, 0);
        //初始化从机
        initSlaveData();
    }

    private void setRecyclerViewPadding(int leftItemPadding, int rightItemPadding) {
        RecyclerView recyclerView = (RecyclerView) controllerViewPager.getChildAt(0);
        recyclerView.setPadding(leftItemPadding, 0, rightItemPadding, 0);
        if (leftItemPadding > 0 || rightItemPadding > 0) {
            recyclerView.setClipToPadding(false);
        } else {
            recyclerView.setClipToPadding(true);
        }
    }




    private void initSlaveData() {
        android.util.Log.i("luzx", "getCurrentItem:" + controllerViewPager.getCurrentItem());
        if (mSmartControlAdapter.getData() == null || mSmartControlAdapter.getData().size() == 0) {
            return;
        }
        ControllerBean host = mSmartControlAdapter.getData().get(controllerViewPager.getCurrentItem());
        if (host == null || TextUtils.isEmpty(host.getControllerSerialNo())) {
            return;
        }
        List<ControllerBean> data = LLControllerDBManager.getInstance(getContext()).getSlaveControllers(host.getControllerSerialNo());
        //分类列表
        List<Map<String, SparseArray<List<ControllerBean>>>> categoryList = new ArrayList<>();
        for (int i = 0; i < LLDeviceUtil.controllerCategoryArray.length; i++) {
            Map<String, SparseArray<List<ControllerBean>>> map = new HashMap<>();
            map.put(LLDeviceUtil.controllerCategoryArray[i], null);
            categoryList.add(map);
        }
        for (ControllerBean slave : data) {
            String typeName = LLDeviceUtil.getControllerTypeName(slave.getProductModel());
            Map<String, SparseArray<List<ControllerBean>>> map = null;
            SparseArray<List<ControllerBean>> sparseArray = null;
            for (Map<String, SparseArray<List<ControllerBean>>> category : categoryList) {
                if (category.keySet().contains(typeName)) {
                    map = category;
                    sparseArray = category.get(typeName);
                    break;
                }
            }
            if (sparseArray == null) {
                sparseArray = new SparseArray<>();
                sparseArray.put(0, new ArrayList<>());//正常智控器
                sparseArray.put(1, new ArrayList<>());//已停用智控器
                map.put(typeName, sparseArray);
            }
            if (slave.isIsDisable()) {
                sparseArray.get(1).add(slave);
            } else {
                sparseArray.get(0).add(slave);
            }
        }

        Iterator<Map<String, SparseArray<List<ControllerBean>>>> iterator = categoryList.iterator();
        while (iterator.hasNext()) {
            Map<String, SparseArray<List<ControllerBean>>> map = iterator.next();
            for (String key : map.keySet()) {
                if (map.get(key) == null) {
                    iterator.remove();
                }
            }
        }
        Log.i("luzx", "categoryList size:" + categoryList.size());
        mSmartControllerCategoryAdapter.setData(categoryList);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshControllerEvent(RefreshControllerEvent event) {
        initData();
        //重新设置，删除控制器后
        controllerViewPager.setCurrentItem(controllerViewPager.getCurrentItem(), false);
        initSlaveData();
    }


    public StatusLayout getStatusLayout() {
        return mStatusLayout;
    }


}